using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using twistmachinev2.CommonUse;
using twistmachinev2.Entity;
using twistmachinev2.OPCUA;
using twistmachinev2.Repository;

namespace twistmachinev2.Business
{
    /// <summary>
    /// OPC UA节点选择器窗体
    /// </summary>
    public partial class FrmNodeSelector : DevExpress.XtraEditors.XtraForm
    {
        private List<OpcUaNodeConfigEntity> _allNodes;
        private List<OpcUaNodeConfigEntity> _filteredNodes;
        private OpcUaConfigService _configService;
        private OPCUARepository _repository;

        /// <summary>
        /// 选中的节点
        /// </summary>
        public OpcUaNodeConfigEntity SelectedNode { get; private set; }

        /// <summary>
        /// 选中的PropertyName
        /// </summary>
        public string SelectedPropertyName { get; private set; }

        public FrmNodeSelector()
        {
            InitializeComponent();
            InitializeForm();
        }

        private void InitializeForm()
        {

            gridView1.OptionsView.ColumnAutoWidth = false;
            // 设置窗体属性
            this.Text = "选择OPC UA节点";
            this.StartPosition = FormStartPosition.CenterParent;
            this.Size = new Size(900, 600);
            this.MinimumSize = new Size(800, 500);

            // 设置样式
            this.LookAndFeel.UseDefaultLookAndFeel = false;
            this.LookAndFeel.SkinName = "Office 2019 Colorful";

            // 设置默认按钮
            this.AcceptButton = btnOK;
            this.CancelButton = btnCancel;
            _repository = new OPCUARepository();
            // 初始化配置服务
            _configService = new OpcUaConfigService(_repository);

            // 设置网格视图属性
            gridView1.OptionsView.ShowGroupPanel = false;
            gridView1.OptionsView.ColumnAutoWidth = false;
            gridView1.OptionsSelection.MultiSelect = false;
            gridView1.OptionsSelection.MultiSelectMode = GridMultiSelectMode.RowSelect;
            gridView1.FocusRectStyle = DrawFocusRectStyle.RowFocus;

            // 双击选择
            gridView1.DoubleClick += GridView1_DoubleClick;

            // 选择变化事件
            gridView1.SelectionChanged += GridView1_SelectionChanged;

            // 初始化搜索框
            txtSearch.Properties.NullText = "输入关键字搜索节点名称、描述或PropertyName...";
            txtSearch.TextChanged += TxtSearch_TextChanged;

            // 初始化分组筛选
            cmbGroup.Properties.NullText = "选择分组筛选";
            cmbGroup.SelectedIndexChanged += CmbGroup_SelectedIndexChanged;
        }

        private async void LoadData()
        {
            try
            {
                // 异步加载数据
                await Task.Run(() =>
                {

                    _allNodes = _configService.GetAllNodes();
                    _filteredNodes = new List<OpcUaNodeConfigEntity>(_allNodes);

                });

                // 更新UI
                this.Invoke(new Action(() =>
                {

                    UpdateGridData();
                    LoadGroups();
                    UpdateStatusInfo();

                }));
            }
            catch (Exception ex)
            {

                // 如果加载失败，自动进行数据库诊断
                XtraMessageBox.Show($"加载节点数据失败：{ex.Message}\n\n点击确定查看数据库诊断信息。", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);

                // 自动执行数据库诊断
                TestDatabaseConnection();
            }
            finally
            {
                // splashScreenManager1.CloseWaitForm();
            }
        }

        private void UpdateGridData()
        {
            try
            {


                // 如果数据为空，记录详细信息
                if (_filteredNodes == null)
                {
                    ;
                }
                else if (_filteredNodes.Count == 0)
                {
                    ;
                }
                else
                {
                    // 记录第一条数据的详细信息
                    var firstNode = _filteredNodes[0];

                }

                // 确保在UI线程中执行
                if (this.InvokeRequired)
                {
                    this.Invoke(new Action(() => UpdateGridData()));
                    return;
                }

                // 先清空数据源
                gridControl1.DataSource = null;

                // 配置列（在绑定数据前配置）,有bug导致不显示
                //ConfigureGridColumns();

                // 重新绑定数据
                gridControl1.DataSource = _filteredNodes;

                // 刷新显示
                gridControl1.RefreshDataSource();
                gridView1.RefreshData();
                gridView1.BestFitColumns();
                // 更新状态信息
                UpdateStatusInfo();
            }
            catch (Exception ex)
            {

                XtraMessageBox.Show($"数据显示失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ConfigureGridColumns()
        {
            try
            {

                gridView1.Columns.Clear();

                // ID列（隐藏）
                var colId = gridView1.Columns.AddField("Id");
                colId.Visible = false;

                // 节点ID列
                var colNodeId = gridView1.Columns.AddField("NodeId");
                colNodeId.Caption = "节点ID";
                colNodeId.Width = 150;
                colNodeId.OptionsColumn.AllowEdit = false;

                // 节点名称列
                var colName = gridView1.Columns.AddField("Name");
                colName.Caption = "节点名称";
                colName.Width = 120;
                colName.OptionsColumn.AllowEdit = false;

                // PropertyName列（重点显示）
                var colPropertyName = gridView1.Columns.AddField("PropertyName");
                colPropertyName.Caption = "属性名称";
                colPropertyName.Width = 120;
                colPropertyName.OptionsColumn.AllowEdit = false;
                colPropertyName.AppearanceCell.BackColor = Color.LightYellow;

                // 描述列
                var colDescription = gridView1.Columns.AddField("Description");
                colDescription.Caption = "描述";
                colDescription.Width = 200;
                colDescription.OptionsColumn.AllowEdit = false;

                // 数据类型列
                var colDataType = gridView1.Columns.AddField("DataType");
                colDataType.Caption = "数据类型";
                colDataType.Width = 80;
                colDataType.OptionsColumn.AllowEdit = false;

                // 分组列
                var colGroup = gridView1.Columns.AddField("Group");
                colGroup.Caption = "分组";
                colGroup.Width = 80;
                colGroup.OptionsColumn.AllowEdit = false;

                // 访问级别列
                var colAccessLevel = gridView1.Columns.AddField("AccessLevel");
                colAccessLevel.Caption = "访问级别";
                colAccessLevel.Width = 80;
                colAccessLevel.OptionsColumn.AllowEdit = false;

                // 是否启用列
                var colEnabled = gridView1.Columns.AddField("IsEnabled");
                colEnabled.Caption = "启用";
                colEnabled.Width = 60;
                colEnabled.OptionsColumn.AllowEdit = false;

                // 自动调整列宽
                gridView1.BestFitColumns();


            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"配置网格列失败：{ex.Message}", "错误",
                     MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

        private void LoadGroups()
        {
            var groups = _allNodes.Where(n => !string.IsNullOrEmpty(n.Group))
                                 .Select(n => n.Group)
                                 .Distinct()
                                 .OrderBy(g => g)
                                 .ToList();

            cmbGroup.Properties.Items.Clear();
            cmbGroup.Properties.Items.Add("全部");
            foreach (var group in groups)
            {
                cmbGroup.Properties.Items.Add(group);
            }

            cmbGroup.SelectedIndex = 0;
        }

        private void UpdateStatusInfo()
        {
            lblStatus.Text = $"共 {_allNodes?.Count ?? 0} 个节点，当前显示 {_filteredNodes?.Count ?? 0} 个";
        }

        private void ApplyFilters()
        {
            if (_allNodes == null) return;

            var searchText = txtSearch.Text.Trim().ToLower();
            var selectedGroup = cmbGroup.Text;

            _filteredNodes = _allNodes.Where(node =>
            {
                // 搜索过滤
                bool matchSearch = string.IsNullOrEmpty(searchText) ||
                                 node.Name?.ToLower().Contains(searchText) == true ||
                                 node.Description?.ToLower().Contains(searchText) == true ||
                                 node.PropertyName?.ToLower().Contains(searchText) == true ||
                                 node.NodeId?.ToLower().Contains(searchText) == true;

                // 分组过滤
                bool matchGroup = selectedGroup == "全部" ||
                                string.IsNullOrEmpty(selectedGroup) ||
                                node.Group == selectedGroup;

                return matchSearch && matchGroup;
            }).ToList();

            UpdateGridData();
            UpdateStatusInfo();
        }

        private void TxtSearch_TextChanged(object sender, EventArgs e)
        {
            ApplyFilters();
        }

        private void CmbGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            ApplyFilters();
        }

        private void GridView1_SelectionChanged(object sender, EventArgs e)
        {
            var selectedNode = GetSelectedNode();
            btnOK.Enabled = selectedNode != null && !string.IsNullOrEmpty(selectedNode.PropertyName);

            // 更新选择信息
            if (selectedNode != null)
            {
                lblSelectedInfo.Text = $"选中: {selectedNode.Name} -> {selectedNode.PropertyName}";
            }
            else
            {
                lblSelectedInfo.Text = "请选择一个节点";
            }
        }

        private void GridView1_DoubleClick(object sender, EventArgs e)
        {
            if (btnOK.Enabled)
            {
                btnOK_Click(sender, e);
            }
        }

        private OpcUaNodeConfigEntity GetSelectedNode()
        {
            var selectedRowHandle = gridView1.FocusedRowHandle;
            if (selectedRowHandle >= 0)
            {
                return gridView1.GetRow(selectedRowHandle) as OpcUaNodeConfigEntity;
            }
            return null;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            var selectedNode = GetSelectedNode();
            if (selectedNode != null && !string.IsNullOrEmpty(selectedNode.PropertyName))
            {
                SelectedNode = selectedNode;
                SelectedPropertyName = selectedNode.PropertyName;

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                XtraMessageBox.Show("请选择一个有效的节点（必须包含PropertyName）！", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                LoadData();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 测试数据库连接和表结构（用于诊断）
        /// </summary>
        private void TestDatabaseConnection()
        {
            try
            {
                using (var testRepository = new OPCUARepository())
                {
                    // 获取数据库信息
                    var dbInfo = testRepository.GetDatabaseInfo();

                    // 检查关键表是否存在
                    var opcUaNodeConfigExists = testRepository.TableExists("OpcUaNodeConfig");
                    var opcUaServerConfigExists = testRepository.TableExists("OpcUaServerConfig");

                    var message = "=== 数据库诊断信息 ===\n\n";
                    message += dbInfo + "\n\n";
                    message += "=== 关键表检查 ===\n";
                    message += $"OpcUaNodeConfig表存在: {opcUaNodeConfigExists}\n";
                    message += $"OpcUaServerConfig表存在: {opcUaServerConfigExists}\n\n";

                    if (!opcUaNodeConfigExists || !opcUaServerConfigExists)
                    {
                        message += "=== 建议操作 ===\n";
                        message += "检测到缺少必要的表，建议执行以下操作：\n";
                        message += "1. 调用 InitializeOpcUaTables() 方法创建表\n";
                        message += "2. 检查数据库文件是否正确\n";
                        message += "3. 确认程序有足够的文件访问权限";
                    }

                    XtraMessageBox.Show(message, "数据库诊断结果",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                var errorMessage = $"数据库诊断失败：\n{ex.Message}\n\n详细信息：\n{ex}";
                XtraMessageBox.Show(errorMessage, "诊断错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

        private void FrmNodeSelector_Load(object sender, EventArgs e)
        {

            try
            {
                LoadData();


            }
            catch (Exception ex)
            {

                MessageBox.Show($"窗体加载失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }



        private void FrmNodeSelector_FormClosing(object sender, FormClosingEventArgs e)
        {
            _configService?.Dispose();
            components?.Dispose();
        }
    }
}